package biz.ezcom.spring.test;

import java.util.Date;
import java.util.List;

import junit.framework.Assert;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import biz.ezcom.spring.datasource.bean.Person;
import biz.ezcom.spring.datasource.dao.PersonDao;

public class Client {
	private static PersonDao personDao = null; 
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-jdbc.xml");
		personDao = (PersonDao) ctx.getBean("personDao");
		personDao.truncate("person");
	}

	@Test
	public void testSave() {
		Person person = new Person();
		person.setUsername("dtc1");
		person.setPassword("zxd1");
		person.setAge(1);
		person.setRegisterDate(new Date());
		personDao.save(person);
		
		person.setUsername("dtc2");
		person.setPassword("zxd2");
		person.setAge(2);
		person.setRegisterDate(new Date());
		personDao.save(person);
	}

	@Test
	public void testUpdate() {
		Person expected = new Person();
		expected.setId(1);
		expected.setUsername("dtcUpdate");
		expected.setPassword("zxdUpdate");
		expected.setAge(81);
		expected.setRegisterDate(new Date());
		personDao.update(expected);
		Person actual = personDao.getPerson(1);
		Assert.assertEquals(expected, actual);
		
	}

	@Test
	public void testGetPerson() {
		Person expected = new Person();
		expected.setId(1);
		Person actual = personDao.getPerson(1);
		Assert.assertNotNull(actual);
	}

	@Test
	public void testGetPersons() {
		List<Person> list = personDao.getPersons();
		Assert.assertNotNull(list);
		Assert.assertTrue(list.size() > 1);
	}

	@Test
	public void testDelete() {
		int id = 1;
		Person p = personDao.getPerson(id);
		Assert.assertNotNull(p);
		personDao.delete(id);
		p = personDao.getPerson(id); //spring JDBC 在get时,如果ResultSet 没有,就会出Exception
		Assert.assertNull(p);
	}

}
